package com.quanyan.stadium.exception.handler;

import com.quanyan.api.APIResponse;
import com.quanyan.api.enums.ApiResponseEnum;
import com.quanyan.common.exception.BizException;
import com.quanyan.stadium.component.asyn.StadiumAsyncService;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;

/**
 *
 * stadium 全局异常捕获,控制器增强,适用于所有使用@ RequestMapping
 * @author songzj
 * @date 16/4/15-11:01
 */
@ControllerAdvice
public class StadiumExceptionHandler {

    private static Logger logger = LoggerFactory.getLogger(StadiumExceptionHandler.class);


    @Value("${log.mail.flag}")
    private boolean logMailFlag;

    @Autowired
    private StadiumAsyncService stadiumAsyncService;

    @ExceptionHandler(Exception.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public ResponseEntity<?> exceptionHandler(HttpServletRequest request, Exception e) {
        if (e instanceof BizException) {
            Object exceptionO = ((BizException) e).getErrorData();
            return new ResponseEntity(APIResponse.returnFail(exceptionO, exceptionO+""), HttpStatus.OK);
        }
        String errorMsg = ExceptionUtils.getStackTrace(e);
        if (logMailFlag && !request.getRequestURI().startsWith("/admin/api/stadium/")) {
            stadiumAsyncService.sendMail(request, errorMsg);
        }
        logger.error("exceptionHandler: stacktrace={}", errorMsg);
        return new ResponseEntity(APIResponse.returnFail(ApiResponseEnum.INTERNAL_ERROR), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
